package com.colorcat.main;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Robot;

import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JLabel;
import javax.swing.JTextField;

import com.colorcat.main.util.GB;
import com.colorcat.mouse.MouseHook;
import com.colorcat.mouse.MouseHookListener;
import com.colorcat.mouse.MouseHookStruct;
import com.sun.jna.platform.win32.WinDef.WPARAM;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Toolkit;
import java.io.File;

import javax.swing.JSeparator;
import javax.swing.JButton;

/**
 * 屏幕取色工具
 * 
 * @author penngo(https://my.oschina.net/penngo)
 * @version 2011.02.15
 */
public class MainWindow extends JFrame {
	private static final long serialVersionUID = 20110116L;
	private MouseHook mouseHook;

	private static Robot robot;
	private JPanel fetchPanel;
	private JTextField textField_Html;
	private JTextField textField_Red;
	private JTextField textField_Green;
	private JTextField textField_Blue;
	private JLabel cruColor;
	private JLabel selectColor;
	private JTextField textField_X;
	private JTextField textField_Y;
	private JButton startBtn;
	private JButton stopBtn;
	private final JTabbedPane tabPanel;
	private boolean isColor = false;
	private String title = "ColorCat 1.0";

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
//			UIManager
//					.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
			UIManager
			.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			new MainWindow();
			

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public MainWindow() throws Exception {
		this.setTitle(title);
//		System.out.println("============" +MainWindow.class.getResource("/"));
		this.setIconImage(Toolkit.getDefaultToolkit().getImage(
				MainWindow.class.getResource("/16.png")));
		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				mouseHook.stopWindowsHookEx();
				deleteFiles();
				System.exit(0);
			}
		});
		tabPanel = new JTabbedPane();
		tabPanel.add("屏幕取色", initFetchPanel());
		tabPanel.add("调色板", initChooserPanel());
		tabPanel.add("配色方案", new NameColorPanel());
		tabPanel.add("颜色转换", new ColorChange());

		tabPanel.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				int index = tabPanel.getSelectedIndex();
				switch (index) {
				case 0:
					MainWindow.this.setSize(310, 250);
					break;
				case 1:
					MainWindow.this.setSize(470, 400);
					break;
				case 2:
					MainWindow.this.setSize(470, 530);
					break;
				case 3:
					MainWindow.this.setSize(417, 300);
					break;
				}
			}
		});
		getContentPane().add(tabPanel, BorderLayout.CENTER);

		this.setSize(310, 250);
//		this.setSize(350, 250);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setAlwaysOnTop(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		
		robot = new Robot();
		new Thread(){
			public void run(){
				mouseHook = new MouseHook();
				mouseHook.addMouseHookListener(new MouseHookListener() {
					public void mouseMove(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
						int x = lParam.x;
						int y = lParam.y;
						//System.out.println("===== x:" + x + ",y:" +y);
						setCurrenColor(x, y);
					}

					public void lButtonDown(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
						int x = lParam.x;
						int y = lParam.y;
						setSelectColor(x, y);
					}

					public void lButtonUp(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
					}

					public void rButtonDown(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
					}

					public void rButtonUp(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
					}

					public void mButtonDown(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
					}

					public void mButtonUp(int nCode, WPARAM wParam,
							MouseHookStruct lParam) {
					}
				});
				mouseHook.startWindowsHookEx();
			}
		}.start();
	}

	public void setSelectColor(int x, int y) {
		if (isColor) {
			Color color = robot.getPixelColor(x, y);
			textField_Red.setText(String.valueOf(color.getRed()));
			textField_Green.setText(String.valueOf(color.getGreen()));
			textField_Blue.setText(String.valueOf(color.getBlue()));
			selectColor.setBackground(color);

			String hex = Integer.toHexString(color.getRGB());
			textField_Html.setText(hex.replaceFirst("ff", "#"));
		}
	}

	public void setCurrenColor(int x, int y) {
		textField_X.setText(String.valueOf(x));
		textField_Y.setText(String.valueOf(y));
		Color color = robot.getPixelColor(x, y);
		cruColor.setBackground(color);
	}

	public JPanel initFetchPanel() {
		fetchPanel = new JPanel();
		fetchPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		fetchPanel.setLayout(null);

		JLabel lblGreen = new JLabel("绿(G)：");
		lblGreen.setBounds(209, 56, 42, 15);
		fetchPanel.add(lblGreen);

		JLabel lblBlue = new JLabel("蓝(B)：");
		lblBlue.setBounds(209, 101, 42, 15);
		fetchPanel.add(lblBlue);
		MyMouseAdapter l = new MyMouseAdapter();
		textField_Red = new JTextField("");
		textField_Red.setBounds(247, 8, 35, 25);
		textField_Red.setEditable(false);
		textField_Red.addMouseListener(l);
		textField_Red.setBorder(BorderFactory.createBevelBorder(1));
		textField_Red.setToolTipText("双击复制文本");
		fetchPanel.add(textField_Red);

		JLabel lblRed = new JLabel("红(R)：");
		lblRed.setBounds(209, 14, 42, 15);
		fetchPanel.add(lblRed);

		textField_Green = new JTextField("");
		textField_Green.setBounds(247, 50, 35, 25);
		textField_Green.setEditable(false);
		textField_Green.addMouseListener(l);
		textField_Green.setBorder(BorderFactory.createBevelBorder(1));
		textField_Green.setToolTipText("双击复制文本");
		fetchPanel.add(textField_Green);

		textField_Blue = new JTextField("");
		textField_Blue.setBounds(247, 95, 35, 25);
		textField_Blue.setEditable(false);
		textField_Blue.addMouseListener(l);
		textField_Blue.setBorder(BorderFactory.createBevelBorder(1));
		textField_Blue.setToolTipText("双击复制文本");
		fetchPanel.add(textField_Blue);

		JLabel lblHtml = new JLabel("HTML：");
		lblHtml.setBounds(15, 53, 40, 15);
		fetchPanel.add(lblHtml);

		textField_Html = new JTextField();
		textField_Html.setBounds(47, 48, 70, 25);
		textField_Html.setEditable(false);
		textField_Html.addMouseListener(l);
		textField_Html.setBorder(BorderFactory.createBevelBorder(1));
		textField_Html.setToolTipText("双击复制文本");
		fetchPanel.add(textField_Html);

		cruColor = new JLabel("");
		cruColor.setBounds(38, 93, 50, 30);
		cruColor.setOpaque(true);
		cruColor.setBorder(BorderFactory.createLineBorder(new Color(128, 128,
				128), 3));
		fetchPanel.add(cruColor);

		selectColor = new JLabel("");
		selectColor.setBounds(130, 93, 50, 30);
		selectColor.setOpaque(true);
		selectColor.setBorder(BorderFactory.createLineBorder(new Color(128,
				128, 128), 3));
		fetchPanel.add(selectColor);

		JLabel label = new JLabel("鼠标位置");
		label.setBounds(6, 12, 55, 18);
		fetchPanel.add(label);

		textField_X = new JTextField();
		textField_X.setEnabled(false);
		textField_X.setEditable(false);
		textField_X.setBounds(85, 8, 38, 25);
		fetchPanel.add(textField_X);

		textField_Y = new JTextField();
		textField_Y.setEnabled(false);
		textField_Y.setEditable(false);
		textField_Y.setBounds(145, 8, 38, 25);
		fetchPanel.add(textField_Y);

		JLabel lblX = new JLabel("X：");
		lblX.setBounds(70, 12, 30, 18);
		fetchPanel.add(lblX);

		JLabel lblY = new JLabel("Y：");
		lblY.setBounds(130, 12, 30, 18);
		fetchPanel.add(lblY);

		JLabel label_1 = new JLabel("当前：");
		label_1.setBounds(6, 99, 41, 18);
		fetchPanel.add(label_1);

		JLabel label_2 = new JLabel("选择：");
		label_2.setBounds(98, 99, 38, 18);
		fetchPanel.add(label_2);

		JSeparator separator = new JSeparator();
		separator.setBounds(6, 135, 276, 2);
		fetchPanel.add(separator);

		startBtn = new JButton("开始取色");
		startBtn.setBounds(6, 150, 90, 30);
		startBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isColor = true;
				startBtn.setEnabled(false);
				stopBtn.setEnabled(true);
			}
		});
		fetchPanel.add(startBtn);

		stopBtn = new JButton("停止取色");
		stopBtn.setBounds(196, 150, 90, 30);
		stopBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isColor = false;
				startBtn.setEnabled(true);
				stopBtn.setEnabled(false);
//				mouseHook.stopWindowsHookEx();
			}
		});
		stopBtn.addMouseListener(new MyMouseAdapter());
		stopBtn.setEnabled(false);
		fetchPanel.add(stopBtn);
		return fetchPanel;
	}

	public JPanel initChooserPanel() {
		JPanel chooserPanel = new JPanel();
		chooserPanel.setLayout(new GridBagLayout());
		JPanel topPanel = new JPanel(new GridBagLayout());
		MyMouseAdapter l = new MyMouseAdapter();
		final JTextField htmlText = new JTextField(7);
		htmlText.setEditable(false);
		htmlText.addMouseListener(l);
		final JTextField redText = new JTextField(3);
		redText.setEditable(false);
		redText.addMouseListener(l);
		final JTextField greenText = new JTextField(3);
		greenText.setEditable(false);
		greenText.addMouseListener(l);
		final JTextField blueText = new JTextField(3);
		blueText.setEditable(false);
		blueText.addMouseListener(l);

		topPanel.add(new JLabel("  HTML:"), new GB(0, 0, 1, 1));
		topPanel.add(htmlText, new GB(1, 0, 1, 1));

		topPanel.add(new JLabel("           红(R):"), new GB(2, 0, 1, 1));
		topPanel.add(redText, new GB(3, 0, 1, 1));

		topPanel.add(new JLabel("  绿(G):"), new GB(4, 0, 1, 1));
		topPanel.add(greenText, new GB(5, 0, 1, 1));

		topPanel.add(new JLabel("  蓝(B):"), new GB(6, 0, 1, 1));
		topPanel.add(blueText, new GB(7, 0, 1, 1));
		topPanel.add(new JLabel(), new GB(8, 0, 1, 1).setFill(GB.BOTH)
				.setWeight(100, 0));

		chooserPanel.add(topPanel, new GB(0, 0, 1, 1).setFill(GB.BOTH)
				.setWeight(100, 0));

		final JLabel colorPan = new JLabel();
		colorPan.setOpaque(true);
		final JLabel textPan = new JLabel("ColorCat", JLabel.RIGHT);
		textPan.setOpaque(true);
		textPan.setFont(new Font("SansSerif", Font.BOLD, 24));
		Color co = textPan.getBackground();

		textPan.setForeground(new Color(co.getRed(), co.getGreen(), co
				.getBlue())); //

		JPanel bannerPanel = new JPanel(new GridBagLayout());
		bannerPanel.add(colorPan, new GB(0, 0, 1, 1).setFill(GB.BOTH)
				.setWeight(100, 100));
		bannerPanel.add(textPan, new GB(1, 0, 1, 1));
		TitledBorder bannerBorder = new TitledBorder("");
		bannerBorder.setTitlePosition(TitledBorder.TOP);
		bannerPanel.setBorder(bannerBorder);

		final JColorChooser tcc = new JColorChooser(textPan.getForeground());
		tcc.getSelectionModel().addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				Color newColor = tcc.getColor();
				colorPan.setBackground(newColor);
				textPan.setForeground(newColor);

				String hex = Integer.toHexString(newColor.getRGB());
				htmlText.setText(hex.replaceFirst("ff", "#"));
				redText.setText(String.valueOf(newColor.getRed()));
				greenText.setText(String.valueOf(newColor.getGreen()));
				blueText.setText(String.valueOf(newColor.getBlue()));
			}
		});

		TitledBorder chooserBorder = new TitledBorder("");
		chooserBorder.setTitlePosition(TitledBorder.TOP);
		AbstractColorChooserPanel[] chooserPanels = tcc.getChooserPanels();
		if (chooserPanels.length > 0) {
			for (AbstractColorChooserPanel p : chooserPanels) {
				p.setBorder(chooserBorder);
			}
		}
		tcc.setPreviewPanel(new JPanel());
		chooserPanel.add(bannerPanel, new GB(0, 1, 1, 1).setFill(GB.BOTH)
				.setWeight(100, 100));
		chooserPanel.add(tcc,
				new GB(0, 2, 1, 1).setFill(GB.BOTH).setWeight(100, 0));
		return chooserPanel;
	}

	public class MyMouseAdapter extends MouseAdapter {
		private Clipboard clipbd = getToolkit().getSystemClipboard();

		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {
				Object obj = e.getSource();
				if (obj instanceof JTextField) {
					JTextField text = (JTextField) obj;

					String select = text.getText();
					text.setSelectionStart(0);
					text.setSelectionEnd(select.length());
					StringSelection clipString = new StringSelection(select);
					clipbd.setContents(clipString, clipString);
				}
			}
		}

		public void mouseEntered(MouseEvent e) {
			if (e.getSource().equals(stopBtn)) {
				isColor = false;
			}
		}

		public void mouseExited(MouseEvent e) {
			if (e.getSource().equals(stopBtn)) {
				if (stopBtn.isEnabled() == true) {
					isColor = true;
				}
			}
		}
	}
	
	public void deleteFiles(){
		File f = new File(".");
		if(f != null && f.listFiles().length > 0){
			for(File c:f.listFiles()){
				if(c.getName().startsWith("hs_err")){
					c.delete();
				}
				
			}
		}

	}
}
